package edu.hunau.cxb19.oop.class32.tcp.v6;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;

/**
 *
 * @author hb
 *
 *         2020-04-21 16:23:09
 */
public class ServerTcp {
	private ServerSocket serverSocket;
	/**
	 * 服务器维护的所有的输出流
	 */
	private List<PrintWriter> casche;

	public ServerTcp() {
		try {
			serverSocket = new ServerSocket(8088);
			casche=new ArrayList<PrintWriter>();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void start() {
		try {
			System.out.println("等待客户端的连接....");
			while (true) {
				Socket socket = serverSocket.accept();
				ClientHandler clientHandler = new ClientHandler(socket);
				// 将获得的Socket实例由线程进行维护
				new Thread(clientHandler).start();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

	/**
	 * 提供一个内部类,创建线程维护一个Socket实例
	 * 
	 * @param args
	 */
	private class ClientHandler implements Runnable {
		private Socket socket;

		public ClientHandler(Socket socket) {
			this.socket = socket;
		}

		@Override
		public void run() {
			PrintWriter pw = null;
			try {
				System.out.println("客户端已经连接!");
				/**
				 * 获得输出流的信息
				 */
				// 向服务器发送消息,获得输出流
				OutputStream os = socket.getOutputStream();
				OutputStreamWriter osw = new OutputStreamWriter(os, "utf-8");
				// 写出数据
				pw = new PrintWriter(osw, true);
				// 将输出流存储到List中
				casche.add(pw);

				// 读取客户端的消息
				InputStream is = socket.getInputStream();
				InputStreamReader isr = new InputStreamReader(is, "utf-8");
				BufferedReader br = new BufferedReader(isr);
				String data = null;
				while ((data = br.readLine()) != null) {
					for (PrintWriter o : casche) {
						o.println(data);
					}
					// 表示客户端下线
					if (data.endsWith("exit")) {
						System.out.println("客户端下线");
						break;
					}
				}
			} catch (IOException e) {
				e.printStackTrace();
			} finally {
				// 当前客户端退出,移除输出流
				casche.remove(pw);
			}
		}
	}

	public static void main(String[] args) {
		ServerTcp server = new ServerTcp();
		server.start();
	}
}
